var mock = require('mock-require');
const assert = require('assert');

mock('co-wechat-oauth', 
    class {

        constructor(appId, appSecret, getToken, saveToken){
            console.log('mock co-wechat-oauth');
            this.getToken = getToken;
            this.saveToken = saveToken;
        }

        getAuthorizeURL(redirect, state, scope) {
            return `http://co-wechat-oauth-mock/getAuthorizeURL?redirect=${encodeURIComponent(redirect)}&state=${encodeURIComponent(state)}&scope=${scope}`;
        }

        async getAccessToken(code) {
            assert(code === 'MOCKCODE');
            const token = { 
                access_token: 'MOCK_ACCESS_TOKEN',
                expires_in: 7200,
                refresh_token: 'MOCK_REFRESH_TOKEN',
                openid: 'MOCK_OPENID',
                scope: 'snsapi_userinfo',
                create_at: Date.now() 
            };
            await this.saveToken(token.openid, token);
            const gotToken = await this.getToken(token.openid);
            assert.deepStrictEqual(gotToken, token, '应该正确存储token');
            return {
                data: token
            };
        }

        async getUser(openid) {
            assert(openid === 'MOCK_OPENID');
            return { 
                openid: 'MOCK_OPENID',
                nickname: 'MOCK_NICKNAME',
                sex: 1,
                language: 'zh_CN',
                city: 'Haidian',
                province: 'Beijing',
                country: 'China',
                headimgurl: '',
                privilege: [] 
            }
        }
    }
);
